package com.qp.basics.admin.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.qp.basics.admin.repository.SysConfigRepository;
import com.qp.basics.admin.service.SysConfigService;
import com.qp.basics.admin.service.dto.SysConfigQueryCriteria;
import com.qp.basics.common.domain.SysConfig;
import com.qp.basics.common.service.dto.SysConfigDto;
import com.qp.basics.common.service.mapstruct.SysConfigMapper;
import com.qp.basics.common.utils.FileUtil;
import com.qp.basics.common.utils.PageUtil;
import com.qp.basics.common.utils.QueryHelp;
import com.qp.basics.common.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.*;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 系统配置
**/
@Service
@RequiredArgsConstructor
public class SysConfigServiceImpl implements SysConfigService {

    private final SysConfigRepository sysConfigRepository;
    private final SysConfigMapper sysConfigMapper;

    @Override
    public Map<String,Object> queryAll(SysConfigQueryCriteria criteria, Pageable pageable){
        Page<SysConfig> page = sysConfigRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(sysConfigMapper::toDto));
    }

    @Override
    public List<SysConfigDto> queryAll(SysConfigQueryCriteria criteria){
        return sysConfigMapper.toDto(sysConfigRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public SysConfigDto findById(Long id) {
        SysConfig sysConfig = sysConfigRepository.findById(id).orElseGet(SysConfig::new);
        ValidationUtil.isNull(sysConfig.getId(),"SysConfig","id",id);
        return sysConfigMapper.toDto(sysConfig);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysConfigDto create(SysConfig resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setId(snowflake.nextId());
        return sysConfigMapper.toDto(sysConfigRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysConfig resources) {
        SysConfig sysConfig = sysConfigRepository.findById(resources.getId()).orElseGet(SysConfig::new);
        ValidationUtil.isNull( sysConfig.getId(),"SysConfig","id",resources.getId());
        resources.setId(sysConfig.getId());
        sysConfigRepository.save(resources);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            sysConfigRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<SysConfigDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SysConfigDto sysConfig : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("模块名称", sysConfig.getCategory());
            map.put("配置名称", sysConfig.getItemName());
            map.put("编辑类型", sysConfig.getEditType());
            map.put("配置值", sysConfig.getItemValue());
            map.put("配置值2", sysConfig.getItemValue2());
            map.put("描述", sysConfig.getDescription());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    @Override
    public JSONObject importExcel(MultipartFile file) {
        JSONObject res=new JSONObject();
/**
        try (InputStream is = file.getInputStream()) {
            ExcelX ex = new ExcelX(is);
            List<Map> l = ex.excelToMapList(0);
            int count=0;
            for (int i = 0; i < l.size(); i++) {
                Map m = l.get(i);
                Object t = m.get("id");
                if (t == null || "".equals(t)) {
                    continue;
                }
                SysConfig q = new SysConfig();
            String category = ImortExportUtil.toStr(m.get("模块名称"));
            q.setCategory(category);
            String itemName = ImortExportUtil.toStr(m.get("配置名称"));
            q.setItemName(itemName);
            String editType = ImortExportUtil.toStr(m.get("编辑类型"));
            q.setEditType(editType);
            String itemValue = ImortExportUtil.toStr(m.get("配置值"));
            q.setItemValue(itemValue);
            String itemValue2 = ImortExportUtil.toStr(m.get("配置值2"));
            q.setItemValue2(itemValue2);
            String description = ImortExportUtil.toStr(m.get("描述"));
            q.setDescription(description);
                q = sysConfigRepository.save(q);
                count++;
            }
            res.put("msg","导入成功：共导入"+count+"条");
        } catch (IOException e) {
            e.printStackTrace();
            res.put("msg","导入失败："+e.getMessage());
        }
            **/
        return res;
    }

    @Override
    public String importItemValue(MultipartFile file) throws IOException {
        //新建存放文件夹
        File file2 =new File("D:\\some\\");
        if(!file2.exists()){
            file2.mkdir();
        }
        String path =null;// 文件路径
        String imgType=null;//图片类型
        if(file != null){
            String fileName = file.getOriginalFilename();// 原文件名称
            // 判断图片类型
            imgType=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
            if(imgType!=null) {
                if ("GIF".equals(imgType.toUpperCase()) || "PNG".equals(imgType.toUpperCase()) || "JPG".equals(imgType.toUpperCase())) {
                    String realPath = "D:\\some\\";
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
                    // 设置图片存放的路径
                    path = realPath + trueFileName;
                    // 转存文件到指定路径
                    file.transferTo(new File(path));
                } else {
                    System.out.println("请上传GIF、PNG或者JPG格式的文件");
                }
            }
        }
        return path;
    }
    /**
     * 获取系统配置信息
     * @param itemName
     * @return
     */
    @Override
    public SysConfig querySysConfigByItemName(String itemName){
        Specification<SysConfig> spec=new Specification<SysConfig>() {
            @Override
            public Predicate toPredicate(Root<SysConfig> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                //1.获取比较的属性
                Path<Object> custName = root.get("itemName");
                //2.构造查询条件
                /** * 第一个参数：须要比较的属性（Path） * 第二个参数：当前比较的取值 */
                Predicate predicate = cb.equal(custName, itemName);//进行精准匹配 （比较的属性，比较的属性的取值）
                return predicate;
            }
        };
        SysConfig info = sysConfigRepository.findOne(spec).get();
        return info;
    }
}
